import React, { Component, Fragment } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { uploadUrl } from '@/config/index'
import {
  Card,
  Tabs,
  message,
  Button,
  Badge,
  Table,
  Tooltip,
  Select,
  Modal,
  Form,
  Input,
  Icon,
  Upload,
  Popconfirm,
  Divider
} from 'antd'
import { connect } from 'dva'
import { LZFormItem } from '@/components/LZForm'
import ConfigService from './services'
import { getToken } from '@/utils/localStorage'

@connect(({ tab }) => ({ ...tab }))
@Form.create()
class TabSetting extends Component {
  state = {
    onChannel: '1',
    onNewChannel: '1', //同步tab modal用的
    visible: false, //modal的控制
    title: '', //modal的标题
    imgSrc: '',
    fileList: [],
    tabActiveKey: '',
    pageNumber: 1,
    pageSize: 10,
    tabInfo: [], //当前tab的信息
    addTabProductVisible: false,
    tabProductVisible: false,
    productInfo: {},
    waitName: [],
    loading: true,
    params: [], //确定同步的参数
    targetChannels: [], //要同步的渠道
    updateConfirmLoading: false,
    addTabConfirmLoading: false,
    newIndexSort: null,
    columnName: '服务位',
    channelData: [],
    tableData: [],
    detail: {}
  }

  columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '店铺营销图名称',
      dataIndex: 'name',
      align: 'center',
      key: 'name'
    },
    {
      title: '营销图片',
      dataIndex: 'imgSrc',
      align: 'center',
      render: text => <img src={text} className="table-cell-img" alt="" />
    },
    {
      title: '跳转链接',
      dataIndex: 'jumpUrl',
      align: 'center',
      key: 'jumpUrl'
    },
    {
      title: '上线时间',
      dataIndex: 'createTime',
      align: 'center',
      key: 'createTime'
    },

    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      key: 'status',
      render: text => {
        const success = text
        const status = success ? 'success' : 'default'
        const badgeText = success ? '有效' : '失效'
        return <Badge status={status} text={badgeText} />
      }
    },
    {
      title: '排序',
      dataIndex: 'indexSort',
      align: 'center',
      key: 'indexSort'
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <div className="table-action">
          <a onClick={() => this.edit(record)}>修改</a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => this.deleteItem(record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      )
    }
  ]

  componentDidMount() {
    this.initData()
  }

  initData = () => {
    let payload = {
      pageNumber: this.state.pageNumber,
      pageSize: this.state.pageSize
    }
    this.setState(
      {
        loading: true
      },
      () => {
        ConfigService.queryOpeIndexShopBannerPage(payload).then(res => {
          message.success('获取信息成功')
          this.setState({
            tableData: res.records,
            total: res.total,
            loading: false,
            current: res.current
          })
        })
      }
    )
  }

  add = () => {
    this.setState({
      visible: true,
      title: '新增配置',
      detail: {}
    })
  }

  deleteItem = record => {
    ConfigService.deleteOpeIndexShopBanner({
      id: record.id
    }).then(res => {
      message.success('删除成功')
      this.initData()
    })
  }

  edit = record => {
    this.setState({
      visible: true,
      detail: record,
      title: '修改配置',
      fileList: [{ uid: record.id, url: record.imgSrc }]
    })
  }
  //modal的确认
  handleOk = () => {
    const { title, detail, imgSrc } = this.state
    const { form } = this.props
    form.validateFields((err, values) => {
      if (!err) {
        const service =
          title === '新增配置'
            ? ConfigService.addOpeIndexShopBanner
            : ConfigService.modifyOpeIndexShopBanner
        service({
          ...values,
          id: detail.id,
          imgSrc: imgSrc ? imgSrc : detail.imgSrc
        })
          .then(res => {
            this.initData()
            message.success('保存成功')
          })
          .finally(() => {
            this.close()
          })
      }
    })
  }

  close = () => {
    this.setState({
      visible: false,
      tabInfo: {},
      fileList: [],
      imgSrc: ''
    })
  }

  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    let filelist = [...fileList] || []
    if (file.status === 'done') {
      filelist.map(item => {
        this.setState({
          imgSrc: item.response.data
        })
      })
    }
    this.setState({
      fileList
    })
  }
  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }
  //上传后下载的回调
  onDownload = file => {
    return window.open(this.state.imgSrc)
  }
  // 上传后删除的回调
  onRemove = () => {
    this.setState({
      fileList: [],
      imgSrc: ''
    })
  }

  //分页，下一页
  onChange = pageNumberber => {
    this.setState(
      {
        pageNumber: pageNumberber
      },
      () => {
        this.initData()
      }
    )
  }
  showTotal = () => {
    return `共有${this.state.total}条`
  }
  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        pageNumber: 1
      },
      () => {
        this.initData()
      }
    )
  }

  render() {
    const { tableData, loading, detail } = this.state
    const {
      visible,
      addTabConfirmLoading,
      title,
      fileList,
      current,
      total,
      tabInfo
    } = this.state
    const {
      name,
      jumpUrl,
      indexSort,
      status = 1,
      imgSrc,
      password,
      confirmPassword
    } = detail
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
      </div>
    )

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Button
            type="primary"
            onClick={this.add}
            className="mb-18"
            style={{ width: 112 }}
          >
            新增
          </Button>
          <Table
            loading={loading}
            columns={this.columns}
            dataSource={tableData}
            rowKey={record => record.id}
            pagination={{
              current: current,
              total: total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['3', '5', '10'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange
            }}
          ></Table>
        </Card>
        {/* 新增 */}
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={addTabConfirmLoading}
          destroyOnClose={true}
          onCancel={this.close}
        >
          <Form {...formItemLayout}>
            <Form.Item label="店铺营销图名称">
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: '店铺营销图名称不能为空'
                  }
                ],
                initialValue: name
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item
              label={
                <Tooltip
                  placement="top"
                  title="/pages/productDetail/index?itemId=（商品编号）"
                >
                  跳转地址{' '}
                  <Icon type="info-circle" style={{ color: '#E83F40' }} />
                </Tooltip>
              }
            >
              {getFieldDecorator('jumpUrl', {
                rules: [
                  {
                    required: true,
                    message: '跳转地址不能为空'
                  }
                ],
                initialValue: jumpUrl
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="排序规则">
              {getFieldDecorator('indexSort', {
                rules: [
                  {
                    required: true,
                    message: '排序不能为空'
                  }
                ],
                initialValue: indexSort
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <LZFormItem
              label="是否生效"
              field="status"
              required
              getFieldDecorator={getFieldDecorator}
              initialValue={status}
            >
              <Select placeholder="请选择" style={{ width: 200 }} allowClear>
                <Select.Option value={0}>无效</Select.Option>
                <Select.Option value={1}>有效</Select.Option>
              </Select>
            </LZFormItem>
            <Form.Item label="营销图片">
              {getFieldDecorator('imgSrc', {
                rules: [
                  {
                    required: true,
                    message: ''
                  },
                  {
                    validator: (rule, value, callback) => {
                      const { form } = this.props
                      if (this.state.imgSrc && !value) {
                        callback('图片不能为空')
                      }
                      callback()
                    }
                  }
                ],
                initialValue: imgSrc
              })(
                <div className="upload-desc">
                  <Upload
                    accept="image/*"
                    action={uploadUrl}
                    headers={{
                      token: getToken()
                    }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview} //预览
                    onRemove={this.onRemove} //删除
                    onDownload={this.onDownload}
                    onChange={this.handleUploadChange}
                  >
                    {fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                  <div className="size-desc">建议尺寸：630px*110px</div>
                </div>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default TabSetting
